import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/call_uil.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/view/leads/leads_follow_up_detail_page.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/tab_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';

import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_colors.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/router_helper.dart';
import '../../../../utils/string_utils.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/status_btn.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_text.dart';
import '../../../../widget/w_toast.dart';
import '../../model/leads.dart';
import '../../model/leads_pool_model.dart';
import '../drive/drive_registration_page.dart';

class LeadsFollowUpPage extends StatefulWidget {
  final String? phone;
  const LeadsFollowUpPage({super.key,this.phone});

  @override
  BaseState<LeadsFollowUpPage> createState() => _LeadsFollowUpPageState();
}

class _LeadsFollowUpPageState extends BaseState<LeadsFollowUpPage> {
  List<Map> dateList = [
    {"title": "全部"},
    {"title": "今日"},
    {"title": "明日"},
    {"title": "未来7天"},
    {"title": "将来"}
  ];
  List<Map> statusList = [
    {"title": "全部",   "value": null},
    {"title": "待跟进", "value": 10161003},
    {"title": "跟进中", "value": 10161004},
    {"title": "转订单", "value": 10161009},
    {"title": "已交付", "value": 10161010}
  ];

  List<Leads> dataList = [];

  Map sortParams = {};
  String autoPhone = "";
  WListViewState? listState;
  Map<String, dynamic> queryParams = {"current": 1, "size": 20};


  @override
  void initState() {
    if (widget.phone != null) {
      queryParams["nameOrPhone"] = widget.phone;
      autoPhone = widget.phone!;
    }
    super.initState();
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "线索管理",
        child: Column(
          children: [
            CustomSearch(
              hintText: "客户名称/手机号",
              initText: autoPhone,
              onSortClick: () {
                WPopupWindow.showSort(
                    context: context,
                    sortType: SortType.LEADS_FOLLOW_UP,
                    sortParams: sortParams,
                    isScrollControlled: true,
                    onSelected: (params) {
                      sortParams = params;
                      print("params$params");
                      params.forEach((key, value) {
                        queryParams[key] = value;
                        if (queryParams.containsKey(key) && value == null) {
                          queryParams.remove(key);
                        }
                      });
                      showLoading();
                      fetchDataList();
                    });
              },
              onTextChange: (text) {
                queryParams["current"] = 1;
                queryParams["nameOrPhone"] = text;
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            TabBtn(
              tabList: dateList,
              tabClick: (index) {
                queryParams["current"] = 1;
                if (index == 0) {
                  queryParams["followDateQuery"] = 5;
                } else if (index == 3) {
                  queryParams["followDateQuery"] = 4;
                } else if (index == 4) {
                  queryParams["followDateQuery"] = 3;
                } else {
                  queryParams["followDateQuery"] = index;
                }
                showLoading();
                fetchDataList();
              },
            ),
            TabBtn(
              tabList: statusList,
              tabClick: (index) {
                queryParams["current"] = 1;
                queryParams["status"] = statusList[index]["value"];
                showLoading();
                fetchDataList();
              },
            ),
            Expanded(
                child: WListView(
              padding: EdgeInsets.zero,
              itemBuilder: _listItem,
              getDataList: (currentStatus, page) {
                listState = currentStatus;
                queryParams["current"] = page;
                fetchDataList();
              },
            ))
          ],
        ));
  }

  void fetchDataList() {
    HttpUtils().post(Api.getFollowClueList, data: queryParams).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        if (value.data != null) {
          setState(() {
            statusList = [
              {"title": "全部",   "value": null},
              {"title": "待跟进 ${value.data["waitFollowNum"] ?? 0}", "value": 10161003},
              {"title": "跟进中 ${value.data["followingNum"] ?? 0}", "value": 10161004},
              {"title": "转订单 ${value.data["toOrderNum"] ?? 0}", "value": 10161009},
              {"title": "已交付 ${value.data["payNum"] ?? 0}", "value": 10161010}
            ];
          });

          List data = value.data["records"] ?? [];
          List<Leads> list = data.map((item) => Leads.fromJson(item)).toList();
          listState?.onRefreshData(list, queryParams["current"]);
          if (queryParams["current"] == 1) {
            dataList.clear();
          }
          dataList.addAll(list);
        }
      } else {
        listState?.onFail(value.errMsg);
      }
    }).catchError((e){
      hideLoading();
      listState?.onFail(e);
    });
  }

  Widget _listItem(context, index, dataList) {
    Leads item = dataList[index];

    String sexStr= CommonReqUtils.exchangeCodeToName(CommonReqUtils.sex, item.sex);
    if (sexStr.isNotEmpty) {
      sexStr = " • $sexStr";
    }

    Map statusStyle = LeadsPoolModel.leadsStatusStyle(
        CommonReqUtils.exchangeCodeToName(
            CommonReqUtils.leadsStatus, item.status));
    return GestureDetector(
        onTap: () => {
              RouteHelper.pushWidget(
                  context,
                  LeadsFollowUpDetailPage(
                    clueId: item.id!,
                  )).then((value) {
                queryParams["current"] = 1;
                fetchDataList();
              })
            },
        child: Container(
          decoration: BoxDecoration(boxShadow: [
            BoxShadow(
                color: WColors.CDFEFFB,
                offset: const Offset(0, 1),
                blurRadius: 3.px)
          ], borderRadius: BorderRadius.circular(10.px), color: Colors.white),
          margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
          padding: EdgeInsets.only(top: 10.px, right: 10.px, bottom: 10.px),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                      child: Row(
                    children: [
                      WLine(
                        width: 4.px,
                        height: 16.px,
                        marginRight: 10.px,
                        color: WColors.primaryColor,
                      ),
                      Flexible(
                        flex: 1,
                        child: WText(
                          item.customerName ?? "",
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: WDimens.tsLarge,
                              color: WColors.mainTextColor,
                              fontWeight: FontWeight.bold),
                        ),
                      ),
                      Flexible(
                        flex: 2,
                        child: WText(
                          sexStr,
                          style: TextStyle(
                              fontSize: WDimens.tsLarge,
                              color: WColors.subTextColor),
                        ),
                      ),
                    ],
                  )),
                  if (item.overdueFlag == true)
                    StatusBtn(
                      text: "已逾期",
                      width: 68.px,
                      height: 28.px,
                      color: WColors.redMain,
                      isTag: true,
                      isItemBtn: true,
                    )
                ],
              ),
              WLine(
                marginTop: 6.px,
                height: 0.5.px,
                marginBottom: 10.px,
                marginLeft: 10.px,
              ),
              Row(
                children: [
                  SizedBox(
                    width: 10.px,
                  ),
                  StatusBtn(
                    height: 24.px,
                    text: CommonReqUtils.exchangeCodeToName(
                        CommonReqUtils.leadsStatus, item.status),
                    color: statusStyle["color"],
                    isTag: true,
                    isItemBtn: true,
                  ),
                  SizedBox(
                    width: 10.px,
                  ),
                  StatusBtn(
                      height: 24.px,
                      width: 32.px,
                      isItemBtn: true,
                      text: CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.intentRange, item.level),
                      // color: priorityStyle["color"],
                      fontColor: WColors.primaryColor,
                      color: WColors.border),
                  SizedBox(
                    width: 10.px,
                  ),
                  StatusBtn(
                    height: 24.px,
                    isItemBtn: true,
                    text: "跟进次数: ${item.followTimes}",
                    color: WColors.orange,
                  ),
                  SizedBox(
                    width: 10.px,
                  ),
                  StatusBtn(
                    height: 24.px,
                    isItemBtn: true,
                    text: CommonReqUtils.exchangeCodeToName(
                        CommonReqUtils.leaderSource, item.clueSource),
                    //  color: sourceStyle["color"],
                    fontColor: WColors.mainTextColor,
                    color: WColors.border,
                  ),
                  SizedBox(
                    width: 10.px,
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  SizedBox(
                    width: 10.px,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [

                      SizedBox(
                        height: 5.px,
                      ),
                      WText(
                        StringUtils.handleThePhoneStr(item.phone) ,
                        style: TextStyle(
                            fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
                      ),
                      SizedBox(
                        height: 5.px,
                      ),
                      Row(
                        children: [
                          WText(
                            item.modelName ?? "",
                            style: TextStyle(
                                fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
                          ),
                          SizedBox(
                            width: 20.px,
                          ),
                          WText(
                            item.salemanName ?? "",
                            style: TextStyle(
                                fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
                          ),
                        ],
                      ),
                      SizedBox(
                        height: 5.px,
                      ),
                      WText(
                        "线索创建:${item.createdAt}",
                        style: TextStyle(
                            fontSize: WDimens.tsMedium,
                            color: WColors.hintTextColor),
                      ),
                      SizedBox(
                        height: 5.px,
                      ),
                      WText(
                        "计划跟进:${item.nextFollowDate}",
                        style: TextStyle(
                            fontSize: WDimens.tsMedium,
                            color: WColors.hintTextColor),
                      ),
                    ],
                  ),
                  Expanded(child: Container()),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      GestureDetector(
                        onTap: () {
                          CallUtil.call(context, item.phone, onBack: (seconds) {
                            showLoading();
                            Map params = {"clueId": item.id, "talkTime": seconds};
                            HttpUtils()
                                .post(Api.addCallLog, data: params)
                                .then((value) {
                              hideLoading();
                              if (value.resultCode == 200) {
                                Toast.toast("电话记录保存成功");
                              } else {
                                Toast.toast(value.errMsg);
                              }
                            });
                          });
                        },
                        child: Container(
                          height: 35.px,
                          width: 35.px,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: WColors.green.withOpacity(0.2),
                              borderRadius: BorderRadius.circular(25.px)),
                          child: Image.asset(
                            "images/phone.png",
                            width: 20.px,
                            color: WColors.green,
                          ),
                        ),
                      ),
                      SizedBox(height: 24.px,),
                      GestureDetector(
                        onTap: () {
                          RouteHelper.pushWidget(context, DriveRegistrationPage(clueCustomerName: item.customerName, cluePhone: item.phone,)).then((value) {
                            queryParams["current"] = 1;
                            fetchDataList();
                          });
                        },
                        child: Container(
                          width: 64.px,
                          alignment: Alignment.center,
                          height: 32.px,
                          decoration: BoxDecoration(
                            color: WColors.primaryColor,
                            borderRadius: BorderRadius.circular(24.px),
                          ),
                          child: WText(
                            "试驾",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: WDimens.tsMedium,
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}
